package com.example.tool.otherui;

import com.example.tool.uicomponents.ButtonController;
import com.jfoenix.controls.JFXListView;
import io.datafx.controller.ViewController;
import io.datafx.controller.flow.Flow;
import io.datafx.controller.flow.FlowException;
import io.datafx.controller.flow.FlowHandler;
import io.datafx.controller.flow.action.ActionTrigger;
import io.datafx.controller.flow.context.FXMLViewFlowContext;
import io.datafx.controller.flow.context.ViewFlowContext;
import io.datafx.controller.util.VetoException;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;

import javax.annotation.PostConstruct;
import java.util.Objects;

@ViewController(value = "/fxml/ui/sideMenu.fxml", title = "侧边栏")
public class SideMenuController {

    @FXMLViewFlowContext
    private ViewFlowContext context;

    @FXML
    @ActionTrigger("tableLogView")
    private Label tableLogView;

    @FXML
    @ActionTrigger("charLogView")
    private Label charLogView;
    @FXML
    @ActionTrigger("taskLogView")
    private Label taskLogView;
    @FXML
    private JFXListView<Label> sideList;

    /**
     * init fxml when loaded.
     */
    @PostConstruct
    public void init() {
        FlowHandler contentFlowHandler = (FlowHandler) context.getRegisteredObject("ContentFlowHandler");
        sideList.propagateMouseEventsToParent();
        sideList.getSelectionModel().selectedItemProperty().addListener((o, oldVal, newVal) -> {
            new Thread(() -> {
                Platform.runLater(() -> {
                    if (newVal != null) {
                        try {
                            contentFlowHandler.handle(newVal.getId());
                        } catch (VetoException exc) {
                            exc.printStackTrace();
                        } catch (FlowException exc) {
                            exc.printStackTrace();
                        }
                    }
                });
            }).start();
        });


        Flow contentFlow = (Flow) context.getRegisteredObject("ContentFlow");
        bindNodeToController(tableLogView, TableViewQueryLogController.class, contentFlow, contentFlowHandler);
        bindNodeToController(charLogView, ChartViewQueryLogController.class, contentFlow, contentFlowHandler);
        bindNodeToController(taskLogView, ButtonController.class, contentFlow, contentFlowHandler);
        System.out.println("加载侧边栏 .............");
    }

    private void bindNodeToController(Node node, Class<?> controllerClass, Flow flow, FlowHandler flowHandler) {
        flow.withGlobalLink(node.getId(), controllerClass);
    }

}
